package com.zzzy.doc.controller.processdoc;

import com.zzzy.common.util.FileUtil;
import com.zzzy.common.vo.AjaxResult;
import com.zzzy.common.vo.PageResult;
import com.zzzy.doc.dao.entity.DocAttachment;
import com.zzzy.doc.service.DocAttachmentService;
import com.zzzy.doc.vo.document.attachment.DocAttachmentPageReq;
import com.zzzy.doc.vo.pageoffice.OpenOfficeFileRes;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

@Tag(name = "办理公文-附件", description = "doc202")
@Validated
@RestController
@RequestMapping("/doc/processDocAttachment")
public class ProcessDocAttachmentController {

    @Resource
    private DocAttachmentService docAttachmentService;

    @Operation(summary = "分页列表")
    @GetMapping(value = "/page")
    @PreAuthorize("@pvs.hasPermission('doc:process:page')")
    public AjaxResult<PageResult<DocAttachment>> page(@Valid @ParameterObject DocAttachmentPageReq queryReq) {
        PageResult<DocAttachment> docAttachmentPage = docAttachmentService.getDocAttachmentPage(queryReq);
        return AjaxResult.success(docAttachmentPage);
    }

    @GetMapping(value = "/getPageOfficeFile/{id}")
    @Operation(summary = "打开文件")
    @Parameter(name = "id", description = "公文附件ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:process:page')")
    public AjaxResult<OpenOfficeFileRes> getPageOfficeFile(@NotNull(message = "公文附件ID不能为空") @PathVariable("id") Long id) {
        String openFileUrl = "/doc/processDocAttachment/getAttachmentFileStream/" + id;
        OpenOfficeFileRes openOfficeFileRes = docAttachmentService.getPageOfficeResByDocId(id, openFileUrl);
        return AjaxResult.success(openOfficeFileRes);
    }

    @GetMapping(value = "/getAttachmentFileStream/{id}")
    @Operation(summary = "获取文件流")
    @Parameter(name = "id", description = "公文附件ID", required = true)
    @PreAuthorize("@pvs.hasPermission('doc:process:page')")
    public void getAttachmentFileStream(@NotNull(message = "公文附件ID不能为空") @PathVariable("id") Long id, HttpServletResponse response) {
        DocAttachment docAttachment = docAttachmentService.getDocAttachmentById(id);
        FileUtil.outputFileStream(response, docAttachment.getFileBlob(), docAttachment.getName());
    }
}
